#pragma once

#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include "oj_control_user.hpp"

namespace ns_view_user
{
    using namespace ns_control_user;
    using namespace boost::asio;
    using namespace boost::beast;
    using namespace boost::asio::ip;

    class UserView
    {
    public:
        UserView(io_context &ioc, tcp::acceptor &acceptor, UserControl &controller)
            : ioc(ioc), acceptor(acceptor), controller(controller) {}

        void start()
        {
            // 监听并接受连接
            acceptor.async_accept([this](boost::beast::error_code ec, tcp::socket socket)
            {
                if (!ec)    handleRequest(std::move(socket));
                start(); // 持续监听下一个请求
            });
        }

    private:
        io_context &ioc;
        tcp::acceptor &acceptor;
        UserControl &controller;

        void handleRequest(tcp::socket socket)
        {
            auto buffer = std::make_shared<boost::beast::flat_buffer>();
            auto req = std::make_shared<http::request<http::string_body>>();
            auto res = std::make_shared<http::response<http::string_body>>();

            // 异步读取 HTTP 请求
            http::async_read(socket, *buffer, *req, 
            [this, socket = std::make_shared<tcp::socket>(std::move(socket)), buffer, req, res](boost::beast::error_code ec, std::size_t bytes_transferred) 
            {
                if (!ec)
                {
                    // 处理路由逻辑
                    route(*req, *res);

                    // 异步写入 HTTP 响应
                    http::async_write(*socket, *res, 
                        [socket, res](boost::beast::error_code ec, std::size_t bytes_transferred) 
                        {
                            if (!ec)
                            {
                                // 关闭 socket
                                boost::system::error_code ignore_ec;
                                socket->shutdown(tcp::socket::shutdown_both, ignore_ec);
                            }
                        });
                }
            }); 
        }

        void route(const http::request<http::string_body> &req, http::response<http::string_body> &res)
        {
            if (req.method() == http::verb::post && req.target() == "/register")
            {
                // 注册用户
                controller.registerUser(req.body(), req.body(), res);
            }
            else if (req.method() == http::verb::post && req.target() == "/login")
            {
                // 登录用户
                controller.loginUser(req.body(), req.body(), res);
            }
            else if (req.method() == http::verb::get && req.target() == "/user")
            {
                // 获取用户信息（从 Cookie 中读取 session_token）
                std::string sessionToken = req[http::field::cookie].to_string();
                controller.getUserInfo(sessionToken, res);
            }
            else
            {
                // 未知路径返回 404
                res.result(http::status::not_found);
                res.body() = "Route not found";
            }
            res.prepare_payload(); // 准备响应的有效负载
        }
    };
}